<?php

namespace app\admin\controller;

use think\Controller;

class Article extends Controller
{
    //文章列表
    public function list(){
        $articleInfo = model("Article")->with('cate_list')->order('is_top', 'desc')->paginate(10);
        $articleInfo->visible(['cate_list' => 'catename']);
        $this->assign("articleInfo", $articleInfo);
        return view();
    }

    //文章添加
    public function add(){
        if (request()->isAjax()){
            $data = [
                'title' => input('post.title'),
                'author' => input('post.author'),
                'tags' => input('post.tags'),
                'is_top' => input('post.is_top',0),
                'cate_id' => input('post.cate_id'),
                'desc' => input('post.desc'),
                'content' => input('post.content')
            ];
            $result = model('article')->add($data);
            if ($result == 1){
                $this->success("文章添加成功", 'admin/article/list');
            }else{
                $this->error($result);
            }
        }
        $cates = model('Cate')->select();
        $this->assign('cates',$cates);
        return view();
    }

    //是否推进
    public function top(){
        $data = [
            'id' => input('post.id'),
            'is_top' => input('post.is_top')
        ];
        $result = model('Article')->top($data);
        if ($result == 1){
            $this->success('操作成功', 'admin/article/list');
        }else{
            $this->error($result);
        }
    }

    //文章编辑
    public function edit(){
        //查询编辑数据
        $articleInfo = model('Article')->with('cate_list')->find(input('id'));
        $this->assign('artInfo', $articleInfo);

        //查询其他所属导航
        $cates = model('Cate')->whereNotIn('id',$articleInfo['cate_list']->id)->select();
        $this->assign('cates', $cates);

        if (request()->isAjax()){
            $data = [
                'id' => input('id'),
                'title' => input('post.title'),
                'tags' => input('post.tags'),
                'is_top' => input('post.is_top',0),
                'cate_id' => input('post.cate_id'),
                'desc' => input('post.desc'),
                'content' => input('post.content')
            ];
            $result = model('Article')->edit($data);
            if ($result==1){
                $this->success('编辑成功', 'admin/article/list');
            }else{
                $this->error($result);
            }

        }
        return view();
    }

    //文章删除
    public function del(){
        $articleInfo = model('Article')->with('comments')->find(input('post.id'));
        $result = $articleInfo->together('comments')->delete();
        if ($result){
            $this->success('删除成功', 'admin/article/list');
        }else{
            $this->error('删除失败');
        }
    }
}
